using System;
using System.Security.Cryptography;
using System.Text;

namespace Glpt.Common
{
    /// <summary>
    /// RSA加密类
    /// </summary>
    public class RSACrypto
    {
        /// <summary>
        /// 字符编码
        /// </summary>
        public Encoding Coding = null;
        /// <summary>
        /// 私钥
        /// </summary>
        public string xmlPrivateKey = null;
        /// <summary>
        /// 公钥
        /// </summary>
        public string xmlPublicKey = null;

        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public RSACrypto()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            this.xmlPrivateKey = rsa.ToXmlString(true);
            this.xmlPublicKey = rsa.ToXmlString(false);
            Coding = new UnicodeEncoding();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="publicKey">公钥</param>
        public void Init(string privateKey, string publicKey)
        {
            this.xmlPrivateKey = privateKey;
            this.xmlPublicKey = publicKey;
        }

        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="txt">要加密的字符串</param>
        /// <returns>加密后字符串</returns>
        public String Encrypt(String txt)
        {
            byte[] bArray = Coding.GetBytes(txt);
            byte[] CypherTextBArray = Encrypt(bArray);
            return Convert.ToBase64String(CypherTextBArray);
        }

        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="bArray">要加密的Byte数组</param>
        /// <returns>加密后的Byte数组</returns>
        public byte[] Encrypt(byte[] bArray)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPublicKey);
            return rsa.Encrypt(bArray, false);
        }

        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="txt">要解密的字符串</param>
        /// <returns>解密后字符串</returns>
        public String Decrypt(String txt)
        {
            byte[] bArray = Convert.FromBase64String(txt);
            byte[] DypherTextBArray = Decrypt(bArray);
            return Coding.GetString(DypherTextBArray);
        }

        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="bArray">要解密的字符串</param>
        /// <returns>解密后字符串</returns>
        public byte[] Decrypt(byte[] bArray)
        {
            if (bArray.Length == 0) return bArray;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);
            return rsa.Decrypt(bArray, false);
        }
    }
}